<template>
  <div class="algorithm-detail">
    <el-skeleton :loading="loading" animated>
      <template #template>
        <div class="skeleton-container">
          <el-skeleton-item variant="p" style="width: 60%" />
          <el-skeleton-item variant="text" style="width: 40%; margin-top: 15px" />
          <el-skeleton-item variant="h3" style="width: 30%; margin-top: 30px" />
          <el-skeleton-item variant="text" style="width: 100%; margin-top: 15px" />
          <el-skeleton-item variant="text" style="width: 100%; margin-top: 8px" />
          <el-skeleton-item variant="text" style="width: 100%; margin-top: 8px" />
        </div>
      </template>

      <template #default>
        <div class="header">
          <el-page-header @back="$router.back()">
            <template #content>
              <span class="page-header__title">{{ caseData.caseName }}</span>
            </template>
          </el-page-header>
        </div>

        <div class="content">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-card class="description-section">
                <template #header>
                  <div class="card-header">
                    <h2>算法描述</h2>
                    <div class="meta-info">
                      <el-tag size="small">创建: {{ formatDate(caseData.createTime) }}</el-tag>
                      <el-tag size="small" type="info">更新: {{ formatDate(caseData.updateTime) }}</el-tag>
                    </div>
                  </div>
                </template>
                <p class="description-text">{{ caseData.description }}</p>
              </el-card>
            </el-col>

            <el-col :span="12">
              <el-card class="code-section">
                <template #header>
                  <div class="card-header">
                    <h2>伪代码实现</h2>
                    <el-button 
                      type="primary" 
                      link 
                      @click="copyToClipboard(caseData.pseudoCode)">
                      复制代码
                    </el-button>
                  </div>
                </template>
                <div class="code-block">
                  <pre><code>{{ caseData.pseudoCode }}</code></pre>
                </div>
              </el-card>
            </el-col>

            <el-col :span="12">
              <el-card class="code-section">
                <template #header>
                  <div class="card-header">
                    <h2>代码实现</h2>
                    <el-button 
                      type="primary" 
                      link 
                      @click="copyToClipboard(caseData.implementation)">
                      复制代码
                    </el-button>
                  </div>
                </template>
                <div class="code-block">
                  <pre><code>{{ caseData.implementation }}</code></pre>
                </div>
              </el-card>
            </el-col>

            <el-col :span="24">
              <el-card class="complexity-section">
                <template #header>
                  <div class="card-header">
                    <h2>复杂度分析</h2>
                  </div>
                </template>
                <div class="complexity-block">
                  <pre><code>{{ caseData.complexityAnalysis }}</code></pre>
                </div>
              </el-card>
            </el-col>

            <el-col :span="24">
              <el-card class="algorithm-cases">
                <template #header>
                  <div class="card-header">
                    <h2>算法案例</h2>
                    <el-form :inline="true" class="search-form">
                      <el-form-item>
                        <el-input
                          v-model="searchForm.caseName"
                          placeholder="搜索案例名称"
                          clearable
                          @keyup.enter="handleSearch"
                        />
                      </el-form-item>
                      <el-form-item>
                        <el-button type="primary" @click="handleSearch">搜索</el-button>
                      </el-form-item>
                    </el-form>
                  </div>
                </template>
                <el-table
                  v-loading="casesLoading"
                  :data="algorithmCases"
                  style="width: 100%"
                  @row-click="handleCaseClick">
                  <el-table-column prop="caseName" label="案例名称" />
                  <el-table-column prop="description" label="描述" show-overflow-tooltip />
                  <el-table-column prop="createTime" label="创建时间" width="180">
                    <template #default="{ row }">
                      {{ formatDate(row.createTime) }}
                    </template>
                  </el-table-column>
                  <el-table-column fixed="right" label="操作" width="120">
                    <template #default="{ row }">
                      <el-button link type="primary" @click.stop="viewCaseDetail(row)">
                        查看详情
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <div class="pagination-container">
                  <el-pagination
                    v-model:current-page="page.current"
                    v-model:page-size="page.size"
                    :page-sizes="[10, 20, 30, 50]"
                    :total="page.total"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                  />
                </div>
              </el-card>
            </el-col>

            <el-col :span="24">
              <el-card class="video-section">
                <template #header>
                  <div class="card-header">
                    <h2>教学视频</h2>
                  </div>
                </template>
                <el-skeleton :loading="videosLoading" animated>
                  <template #template>
                    <div class="video-skeleton">
                      <el-skeleton-item variant="image" style="width: 240px; height: 135px" />
                      <el-skeleton-item variant="p" style="width: 200px; margin-top: 8px" />
                      <el-skeleton-item variant="text" style="width: 160px; margin-top: 8px" />
                    </div>
                  </template>
                  <template #default>
                    <div v-if="videos.length === 0" class="no-videos">
                      <el-empty description="暂无教学视频" />
                    </div>
                    <div v-else class="video-list">
                      <div v-for="video in videos" :key="video.videoId" class="video-item">
                        <div class="video-thumbnail">
                          <el-image 
                            :src="generateThumbnail(video.videoUrl)"
                            fit="cover"
                            :preview-src-list="[]">
                            <template #error>
                              <div class="video-placeholder">
                                <el-icon><VideoCamera /></el-icon>
                              </div>
                            </template>
                          </el-image>
                          <span class="video-duration">{{ formatDuration(video.duration) }}</span>
                        </div>
                        <div class="video-info">
                          <h3 class="video-title">{{ video.videoTitle }}</h3>
                          <p class="video-description">{{ video.videoDescription }}</p>
                          <el-button 
                            type="primary" 
                            link 
                            @click="watchVideo(video)">
                            观看视频
                          </el-button>
                        </div>
                      </div>
                    </div>
                  </template>
                </el-skeleton>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </template>
    </el-skeleton>

    <el-dialog
      v-model="videoDialogVisible"
      :title="currentVideo?.videoTitle"
      width="80%"
      class="video-dialog"
      :before-close="handleCloseVideo">
      <div class="video-player">
        <iframe
          v-if="currentVideo"
          :src="currentVideo.videoUrl"
          frameborder="0"
          allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
          allowfullscreen>
        </iframe>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import { VideoCamera } from '@element-plus/icons-vue'

export default {
  name: 'AlgorithmDetail',
  components: {
    VideoCamera
  },
  data() {
    return {
      caseData: {
        caseId: 0,
        typeId: 0,
        caseName: '加载中...',
        description: '',
        pseudoCode: '',
        implementation: '',
        complexityAnalysis: '',
        createTime: '',
        updateTime: ''
      },
      loading: true,
      videos: [],
      videosLoading: true,
      videoDialogVisible: false,
      currentVideo: null,
      algorithmCases: [],
      casesLoading: false,
      page: {
        current: 1,
        size: 10,
        total: 0
      },
      searchForm: {
        caseName: '',
        typeId: null
      }
    }
  },
  watch: {
    '$route.params.typeId': {
      handler(newTypeId) {
        if (newTypeId) {
          this.searchForm.typeId = parseInt(newTypeId)
          this.fetchCaseDetail()
          this.fetchVideos()
          this.fetchCases()
        }
      },
      immediate: true
    }
  },
  methods: {
    async fetchCaseDetail() {
      try {
        this.loading = true
        const typeId = this.$route.params.typeId
        const params = {
          page: 1,
          size: 1,
          typeId: typeId
        }
        
        const response = await axios.get('/api/algorithm-cases/page', { params })
        if (response.data.code === 200 && response.data.data?.records?.length > 0) {
          await this.viewCaseDetail({ caseId: response.data.data.records[0].caseId })
        } else {
          // 当没有数据时，展示默认内容
          const defaultContents = {
            1: {
              caseName: '分治算法示例',
              description: '分治算法的核心思想是将一个复杂的问题分解成若干个规模较小的相同问题，递归解决这些子问题，然后将子问题的解合并得到原问题的解。',
              pseudoCode: 'divide_and_conquer(problem):\n  if problem is small enough:\n    solve problem directly\n  else:\n    divide problem into smaller subproblems\n    recursively solve each subproblem\n    combine solutions of subproblems',
              implementation: '// 分治算法通用模板\nfunction divideAndConquer(problem) {\n  if (isSmallEnough(problem)) {\n    return solveDirect(problem);\n  } else {\n    const subproblems = divide(problem);\n    const subresults = subproblems.map(divideAndConquer);\n    return combine(subresults);\n  }\n}',
              complexityAnalysis: '时间复杂度：取决于具体问题\n空间复杂度：通常需要额外的递归栈空间'
            },
            2: {
              caseName: '动态规划示例',
              description: '动态规划通过将原问题分解为相对简单的子问题的方式求解复杂问题。它的核心思想是通过存储子问题的解来避免重复计算。',
              pseudoCode: 'dynamic_programming():\n  initialize dp array\n  for each subproblem:\n    solve using previous results\n    store result in dp array\n  return final result',
              implementation: '// 动态规划通用模板\nfunction dynamicProgramming(problem) {\n  const dp = initializeArray(problem.size);\n  \n  // 初始化基础情况\n  initializeBaseCase(dp);\n  \n  // 填充dp数组\n  for (let i = 1; i < problem.size; i++) {\n    dp[i] = calculateFromPrevious(dp, i);\n  }\n  \n  return dp[problem.size - 1];\n}',
              complexityAnalysis: '时间复杂度：通常为 O(n) 或 O(n²)\n空间复杂度：通常为 O(n)'
            },
            3: {
              caseName: '贪心算法示例',
              description: '贪心算法在每一步选择中都采取当前状态下最好或最优的选择，从而希望导致结果是最好或最优的算法。',
              pseudoCode: 'greedy_algorithm():\n  initialize result\n  while problem is not solved:\n    make locally optimal choice\n    add to result\n  return result',
              implementation: '// 贪心算法通用模板\nfunction greedyAlgorithm(problem) {\n  const result = [];\n  \n  while (!isSolved(problem)) {\n    const bestChoice = findBestChoice(problem);\n    result.push(bestChoice);\n    updateProblem(problem, bestChoice);\n  }\n  \n  return result;\n}',
              complexityAnalysis: '时间复杂度：通常为 O(n) 或 O(n log n)\n空间复杂度：通常为 O(1) 或 O(n)'
            },
            4: {
              caseName: '回溯算法示例',
              description: '回溯算法是一种通过探索所有可能的候选解来找出所有解的算法。它采用试错的思想，尝试分步解决一个问题，在分步解决问题的过程中，当发现当前的分步答案不能得到有效的正确的解答时，将取消上一步或几步的计算，再通过其他的可能的分步解答再次尝试寻找问题的答案。',
              pseudoCode: 'backtrack(candidates):\n  if found a solution:\n    add to result\n    return\n  \n  for each possible choice:\n    if choice is valid:\n      make choice\n      backtrack(remaining candidates)\n      undo choice',
              implementation: '// 回溯算法通用模板\nfunction backtrack(candidates, current = [], result = []) {\n  if (isSolution(current)) {\n    result.push([...current]);\n    return;\n  }\n  \n  for (const choice of candidates) {\n    if (isValid(choice, current)) {\n      current.push(choice);\n      backtrack(candidates, current, result);\n      current.pop();\n    }\n  }\n}',
              complexityAnalysis: '时间复杂度：通常为指数级 O(2^n) 或更高\n空间复杂度：通常为 O(n)，用于递归栈'
            }
          };

          const defaultContent = defaultContents[typeId] || {
            caseName: '算法示例',
            description: '这是一个算法示例页面，展示了算法的基本结构和实现方式。',
            pseudoCode: '// 基本算法结构\nfunction algorithm(input):\n  process input\n  return result',
            implementation: '// 基本实现\nfunction algorithm(input) {\n  // 处理输入\n  const result = processInput(input);\n  return result;\n}',
            complexityAnalysis: '时间复杂度：待分析\n空间复杂度：待分析'
          };

          this.caseData = {
            ...this.caseData,
            ...defaultContent,
            createTime: new Date().toISOString(),
            updateTime: new Date().toISOString()
          }
        }
      } catch (error) {
        console.error('请求失败:', error)
        this.caseData = {
          ...this.caseData,
          caseName: '加载失败',
          description: '数据加载失败，请稍后重试'
        }
        this.$message.error('请求失败，请检查网络连接')
      } finally {
        this.loading = false
      }
    },
    formatDate(dateString) {
      if (!dateString) return '暂无时间信息'
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    },
    copyToClipboard(text) {
      navigator.clipboard.writeText(text).then(() => {
        this.$message.success('代码已复制到剪贴板')
      }).catch(() => {
        this.$message.error('复制失败，请手动复制')
      })
    },
    async fetchVideos() {
      try {
        this.videosLoading = true
        const typeId = this.$route.params.typeId
        const response = await axios.get(`/api/teaching-videos/by-type/${typeId}`)
        
        if (response.data.code === 200 && response.data.data) {
          this.videos = response.data.data
        } else {
          this.videos = []
        }
      } catch (error) {
        console.error('获取视频列表失败:', error)
        this.$message.error('获取视频列表失败，请稍后重试')
        this.videos = []
      } finally {
        this.videosLoading = false
      }
    },
    generateThumbnail(videoUrl) {
      // 这里可以根据实际情况生成缩略图URL
      // 如果视频平台提供缩略图API，可以使用实际的缩略图
      return `${videoUrl}/thumbnail`
    },
    formatDuration(seconds) {
      const minutes = Math.floor(seconds / 60)
      const remainingSeconds = seconds % 60
      return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
    },
    watchVideo(video) {
      this.currentVideo = video
      this.videoDialogVisible = true
    },
    handleCloseVideo(done) {
      this.currentVideo = null
      done()
    },
    async fetchCases() {
      try {
        this.casesLoading = true
        const params = {
          page: this.page.current,
          size: this.page.size,
          typeId: this.searchForm.typeId,
          caseName: this.searchForm.caseName || undefined
        }

        const response = await axios.get('/api/algorithm-cases/page', { params })
        
        if (response.data.code === 200 && response.data.data) {
          const { records, total, current, size } = response.data.data
          this.algorithmCases = records
          this.page.total = total
          this.page.current = current
          this.page.size = size
        } else {
          this.$message.warning('获取案例列表失败')
        }
      } catch (error) {
        console.error('获取案例列表失败:', error)
        this.$message.error('获取案例列表失败，请稍后重试')
      } finally {
        this.casesLoading = false
      }
    },
    handleSearch() {
      this.page.current = 1
      this.fetchCases()
    },
    handleSizeChange(val) {
      this.page.size = val
      this.fetchCases()
    },
    handleCurrentChange(val) {
      this.page.current = val
      this.fetchCases()
    },
    handleCaseClick(row) {
      this.viewCaseDetail(row)
    },
    async viewCaseDetail(row) {
      try {
        this.loading = true
        const response = await axios.get(`/api/algorithm-cases/${row.caseId}`)
        if (response.data.code === 200) {
          if (response.data.data) {
            this.caseData = response.data.data
            this.$message.success('加载案例详情成功')
          } else {
            this.$message.warning('暂无该案例的详细信息')
            this.caseData = {
              caseName: '暂无数据',
              description: '暂无描述',
              pseudoCode: '',
              implementation: '',
              complexityAnalysis: '',
              createTime: '',
              updateTime: ''
            }
          }
        } else {
          this.$message.error(response.data.message || '获取案例详情失败')
        }
      } catch (error) {
        console.error('获取案例详情失败:', error)
        this.$message.error('获取案例详情失败，请稍后重试')
        this.caseData = {
          caseName: '加载失败',
          description: '数据加载失败，请稍后重试',
          pseudoCode: '',
          implementation: '',
          complexityAnalysis: '',
          createTime: '',
          updateTime: ''
        }
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style scoped>
.algorithm-detail {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.skeleton-container {
  padding: 20px;
}

.header {
  margin-bottom: 30px;
}

.page-header__title {
  font-size: 20px;
  font-weight: bold;
  color: #2c3e50;
}

.content {
  margin-top: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.card-header h2 {
  margin: 0;
  font-size: 1.2em;
  color: #2c3e50;
}

.meta-info {
  display: flex;
  gap: 10px;
}

.description-text {
  line-height: 1.6;
  color: #2c3e50;
  font-size: 16px;
}

.code-block, .complexity-block {
  background-color: #1e1e1e;
  border-radius: 6px;
  padding: 15px;
  margin: 0;
}

pre {
  margin: 0;
  white-space: pre-wrap;
}

code {
  font-family: 'Fira Code', 'Courier New', Courier, monospace;
  font-size: 14px;
  line-height: 1.6;
  color: #d4d4d4;
}

:deep(.el-card) {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f8f9fa;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-tag) {
  margin-right: 8px;
}

.el-row {
  margin: -10px;
}

.el-col {
  padding: 10px;
}

@media (max-width: 768px) {
  .el-col {
    width: 100% !important;
  }
}

.video-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.video-item {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
  transition: transform 0.3s ease;
}

.video-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.video-thumbnail {
  position: relative;
  width: 100%;
  padding-top: 56.25%; /* 16:9 aspect ratio */
}

.video-thumbnail .el-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.video-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 24px;
}

.video-duration {
  position: absolute;
  bottom: 8px;
  right: 8px;
  background-color: rgba(0, 0, 0, 0.75);
  color: white;
  padding: 2px 4px;
  border-radius: 2px;
  font-size: 12px;
}

.video-info {
  padding: 12px;
}

.video-title {
  margin: 0 0 8px;
  font-size: 16px;
  font-weight: 500;
  color: #2c3e50;
}

.video-description {
  margin: 0 0 12px;
  font-size: 14px;
  color: #606266;
  line-height: 1.4;
}

.no-videos {
  padding: 40px 0;
}

.video-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.video-player {
  position: relative;
  width: 100%;
  padding-top: 56.25%;
}

.video-player iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

@media (max-width: 768px) {
  .video-list {
    grid-template-columns: 1fr;
  }
}

.search-form {
  display: flex;
  align-items: center;
  gap: 10px;
}

.algorithm-cases {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table) {
  margin-top: 20px;
}

:deep(.el-table__row) {
  cursor: pointer;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}
</style> 